package com.pingao.mp.modular.common.controller;

import com.pingao.mp.config.MpConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping(value = "/common/upload")
@Controller
public class UploadController {

    @Autowired
    private MpConfig mpConfig;

    @PostMapping(value = "/upload")
    @ResponseBody
    public Object upload(@RequestParam(value = "file") MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("filePath", handle(file));
            map.put("result", "ok");
        } catch (Exception ex) {
            map.put("result", "fail");
            map.put("message", ex.getMessage());
        }
        return map;
    }

    /**
     * 富文本编辑器文件（图片和附件）处理
     * @param file 表单文件
     * @return 前台需要的json数据
     */
    @PostMapping(value = "/ckeditor")
    @ResponseBody
    public Object ckeditor(@RequestParam(value = "upload") MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("uploaded", 1);
            map.put("fileName", "上传成功");
            map.put("url", request.getContextPath() + handle(file));
        } catch (Exception ex) {
            map.put("uploaded", 0);
            Map<String, Object> p = new HashMap<>();
            p.put("message", ex.getMessage());
            map.put("error", p);
        }
        return map;
    }

    /**
     * 处理文件上传
     *
     * @param file 文件
     * @return 上传服务器路径
     * @throws Exception 上传错误信息
     */
    private String handle(MultipartFile file) throws Exception {
        if (file == null) {
            throw new Exception("上传文件为空");
        } else {
            String oldFileName = file.getOriginalFilename();
            assert oldFileName != null;
            String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + eName;
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            int day = cal.get(Calendar.DATE);
            int hour = cal.get(Calendar.HOUR_OF_DAY);
            String p = System.getProperty("user.dir");

            String filePath = "/" + mpConfig.getFilePath() + "/" + +year + "/" + month + "/" + day + "/" + hour;
            File newFile = new File(p + filePath);
            if (!newFile.exists()) {
                boolean mkdirs = newFile.mkdirs();
                if (!mkdirs) {
                    throw new Exception("创建目录失败");
                }
            }
            File fileImg = new File(newFile, newFileName);
            //写入文件
            file.transferTo(fileImg);
            return filePath + "/" + newFileName;
        }
    }
}
